import request from '../utils/request';
import { ElMessage } from 'element-plus';

// 获取抽奖活动列表
export function getLotteryList(params) {
    console.log('调用getLotteryList API，参数:', params);
    return request({
        url: '/api/lottery',
        method: 'get',
        params: {
            ...params,
            includeParticipants: true
        }
    }).then(response => {
        console.log('getLotteryList API响应:', response);
        return response;
    }).catch(error => {
        console.error('getLotteryList API错误:', error);
        throw error;
    });
}

// 获取抽奖活动详情
export function getLotteryDetail(id) {
    return request({
        url: `/api/lottery/${id}`,
        method: 'get'
    });
}

// 创建抽奖活动
export function createLottery(data) {
    return request({
        url: '/api/lottery',
        method: 'post',
        data
    });
}

// 发布抽奖活动
export const publishLotteryApi = async (id) => {
    try {
        const response = await request({
            url: `/api/lottery/${id}/publish`,
            method: 'post'
        });

        // 检查是否有警告信息需要展示
        if (response.data.warning) {
            ElMessage.warning(response.data.warning);
        }

        return response;
    } catch (error) {
        console.error('发布抽奖失败:', error);
        throw error;
    }
};

// 手动开奖
export function drawLottery(id) {
    console.log('调用手动开奖API，抽奖ID:', id);

    return request({
        url: `/api/lottery/${id}/draw`,
        method: 'post'
    }).then(response => {
        console.log('开奖API响应:', response);
        return response; // 返回完整响应以便错误处理
    }).catch(error => {
        console.error('开奖API错误:', error);
        throw error; // 传递错误以便上层处理
    });
}

// 取消抽奖活动
export function cancelLottery(id) {
    return request({
        url: `/api/lottery/${id}/cancel`,
        method: 'post'
    });
}

// 获取抽奖活动参与者
export function getLotteryParticipants(id) {
    return request({
        url: `/api/lottery/${id}/participants`,
        method: 'get'
    });
}

// 获取抽奖活动状态统计
export function getLotteryStats(groupId) {
    return request({
        url: '/api/lottery/stats',
        method: 'get',
        params: { groupId }
    });
}

// 轮询抽奖参与者
export function pollLotteryParticipants(lotteryId, interval = 5000) {
    const controller = new AbortController();
    const signal = controller.signal;

    const poll = async (callback) => {
        try {
            const response = await request({
                url: `/api/lottery/${lotteryId}/participants`,
                method: 'get',
                signal
            });

            if (response && response.data) {
                callback(response.data);
            }

            // 持续轮询
            setTimeout(() => poll(callback), interval);
        } catch (error) {
            // 如果不是手动中止，则继续轮询
            if (error.name !== 'AbortError') {
                console.error('轮询抽奖参与者失败:', error);
                setTimeout(() => poll(callback), interval);
            }
        }
    };

    return {
        start: (callback) => poll(callback),
        stop: () => controller.abort()
    };
}

// 获取抽奖记录列表
export function getLotteryRecords(params) {
    console.log('调用getLotteryRecords API，参数:', params);
    return request({
        url: '/api/lottery/records',
        method: 'get',
        params
    }).then(response => {
        console.log('getLotteryRecords API响应:', response);
        return response;
    }).catch(error => {
        console.error('getLotteryRecords API错误:', error);
        throw error;
    });
} 